// OGoMojo
// Whitemice.MOGI.MOGIMon
// License: LGPL
// Copyright: Whitemice Consulting, 2006
// Author(s): Adam Tauno Williams (awilliam@whitemice.org)
using System;
using System.Net;
using System.Threading;
using System.Collections;
using Whitemice.MOGI;
using Whitemice.MOGI.RPC2;

namespace Whitemice.MOGI.MOGIMon
{
	public class MOGIMonEXE
	{
		IServer				server;
		int						delay;
		Auditor				auditor;
		RecordKeeper	keeper;
		Worker				worker;
	
		public static void Main()
		{
			MOGIMonEXE daemon;
			daemon = new MOGIMonEXE();
			daemon.Run();
		}
		
		public MOGIMonEXE()
		{
			server = new Whitemice.MOGI.RPC2.Server("OGoMojo.log");
			server.Hostname = server.GetDirectiveValue("MOGIMon", "Hostname");			
			server.Credentials = new NetworkCredential(
				server.GetDirectiveValue("MOGIMon", "Username"),
				server.GetDirectiveValue("MOGIMon", "Secret"));
			if (!server.Connected)
			{
				Console.WriteLine("Unable to connect to groupware server");
				Thread.CurrentThread.Abort();
			}		
			keeper = new RecordKeeper(server);
			keeper.Connect();
			auditor = new Auditor(server, keeper);
			auditor.Connect();
			worker = new Worker(server, keeper);
			worker.Load();
			delay = Convert.ToInt32(server.GetDirectiveValue("MOGIMon", "LoopDelay"));
		}
				
		public void Run()
		{
			Hashtable 	changes;
			int			iterCount;
			
			iterCount = 0;
			while ( true )
			{
				changes = auditor.Changes;
				foreach(string documentName in changes.Keys)
					worker.Do((Change)changes[documentName]);
				iterCount++;
				Thread.Sleep(delay);
			}
		}
	}
}
